package com.yzmoney.wechat.service;

import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.util.FileUtil;
import com.yzmoney.common.util.HttpClientUtils;
import com.yzmoney.common.util.JsonUtils;
import com.yzmoney.wechat.model.WechatType;
import com.yzmoney.wechat.model.general.GeneralReturnCode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 创建微信公众号菜单service
 * 
 * @author DOVE
 */

@Service
public class WechatMenuService {
	private static final Log log = LogFactory.getLog(WechatMenuService.class);

	@Autowired
	private WechatAccessTokenService wechatAccessTokenService;

	private static String baseCreatMenuUrl = PropertyUtils.getValue(
			"MENU_CREATE_URL", "", Constants.GZH_PATH);

	private static String menuPath = PropertyUtils.getValue("menuPath", "",
			Constants.GZH_PATH);

	/**
	 * 创建菜单
	 */
	public void createMenu(String type) {
		log.info("创建菜单   begin");
		WechatType wType = null;
		String jsonString = "";
		if (type.equals("qyh")) {
			wType = WechatType.QYH;

		} else if (type.equals("gzh")) {
			wType = WechatType.GZH;
			jsonString = getMenuJson();
			if (JsonUtils.jsonValidate(jsonString)) {
				String accessToken = wechatAccessTokenService
						.getGZHAccessToken();
				String url = getCreateMenuUrl(accessToken);
				String resultString = HttpClientUtils.post(url, jsonString);
				GeneralReturnCode generalReturnCode = JsonUtils.toObject(
						resultString, GeneralReturnCode.class);
				if (generalReturnCode.getErrcode().equals("0")) {
					log.info(Constants.LOGPRIFIX + "创建菜单[成功end menuJson:"
							+ jsonString);
				} else {
					log.info(Constants.LOGPRIFIX + "创建菜单[失败]end  "
							+ generalReturnCode.toString() + ", menuJson:"
							+ jsonString);
				}
			} else {
				log.info(Constants.LOGPRIFIX + "创建菜单[失败]end menuJson:"
						+ jsonString);
			}
		}

	}

	/**
	 * 拼接公众号 生成菜单请求地址
	 * 
	 * @return
	 */
	private static String getCreateMenuUrl(String accessToken) {
		String createMenuUrl = baseCreatMenuUrl + "?access_token="
				+ accessToken;
		return createMenuUrl;
	}

	/**
	 * 获取menu菜单json
	 * 
	 * @return
	 */
	private static String getMenuJson() {
		return FileUtil.readFile(FileUtil.getWebInfoPath() + menuPath);
	}

}
